package com.bd.scm.module.role.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bd.scm.dao.mapper.role.BdRoleMainMapper;
import com.bd.scm.domain.dto.TreeNode;
import com.bd.scm.domain.models.role.BdRoleMain;
import com.bd.scm.module.role.service.BdRoleMainService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Mason
 * @since 2021-01-11
 */
@Service
public class BdRoleMainServiceImpl extends ServiceImpl<BdRoleMainMapper, BdRoleMain> implements BdRoleMainService {

    @Resource
    private BdRoleMainMapper bdRoleMainMapper;

    /**
     * 获取权限组的树结构数据（只有key、title、children）
     *
     * @return
     */
    @Override
    public List<TreeNode> getRoleMainTreeAll() {
        List<BdRoleMain> bdRoleMainList = this.list();
        //TODO 抛出空数据异常
        if (CollectionUtils.isEmpty(bdRoleMainList)) return null;
        List<TreeNode> treeList = createTree(0L, bdRoleMainList);
        return treeList;

    }

    /**
     * 递归生成树（只有key、title、children）
     *
     * @param parentId  父级ID
     * @param bdRoleMainList 全部数据
     * @return
     */
    private List<TreeNode> createTree(Long parentId, List<BdRoleMain> bdRoleMainList) {
        List<BdRoleMain> parentList = bdRoleMainList.stream().filter(a -> Long.parseLong(a.getParentId().toString()) ==
                parentId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(parentList)) return null;
        List<TreeNode> listRtn = new ArrayList<>();
        parentList.forEach(row -> {

            TreeNode treeNode = new TreeNode();
            treeNode.setKey(row.getId().toString());
            treeNode.setTitle(row.getRoleName());//一卡通系统
            treeNode.setText(row.getRoleName());//法雷奥系统
            treeNode.setValue(row.getId().toString());//法雷奥系统
            treeNode.setSelectable(parentId==0L?false:true);//根节点禁止点选
            treeNode.setChildren(createTree(Long.parseLong(row.getId().toString()), bdRoleMainList));
            listRtn.add(treeNode);
        });
        return listRtn;
    }
}
